"use client"

import type { ReactNode } from "react"
import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { apiCall, mockGenerators } from "@/lib/mock-api"
import { Skeleton } from "@/components/ui/skeleton"

type AuthState = "checking" | "authorized" | "unauthorized"

interface DriveAuthGuardProps {
  children: ReactNode
}

export function DriveAuthGuard({ children }: DriveAuthGuardProps) {
  const router = useRouter()
  const [authState, setAuthState] = useState<AuthState>("checking")

  useEffect(() => {
    let cancelled = false

    const verifyAuth = async () => {
      const token = localStorage.getItem("driveJWTToken")
      if (!token) {
        if (!cancelled) {
          setAuthState("unauthorized")
        }
        return
      }

      try {
        await apiCall(
          "/api/auth/info",
          undefined,
          undefined,
          mockGenerators.currentUser,
        )

        if (!cancelled) {
          setAuthState("authorized")
        }
      } catch (error) {
        console.error("登录校验失败：", error)
        localStorage.removeItem("driveJWTToken")
        if (!cancelled) {
          setAuthState("unauthorized")
        }
      }
    }

    verifyAuth()

    return () => {
      cancelled = true
    }
  }, [])

  useEffect(() => {
    if (authState === "unauthorized") {
      router.replace("/login")
    }
  }, [authState, router])

  if (authState === "checking") {
    return <DriveSkeleton />
  }

  if (authState === "authorized") {
    return <>{children}</>
  }

  return <DriveSkeleton />
}

function DriveSkeleton() {
  const rows = Array.from({ length: 6 })

  return (
    <div className="flex h-screen bg-background">
      <div className="hidden w-64 flex-shrink-0 flex-col border-r border-border bg-card p-6 md:flex">
        <Skeleton className="h-8 w-32 rounded-lg bg-muted" />
        <div className="mt-6 space-y-3">
          <Skeleton className="h-8 w-full bg-muted/90" />
          <Skeleton className="h-8 w-3/4 bg-muted/90" />
        </div>
        <div className="mt-auto pt-6">
          <Skeleton className="h-8 w-full bg-muted/90" />
        </div>
      </div>
      <div className="flex flex-1 flex-col overflow-hidden">
        <header className="flex h-16 items-center gap-4 border-b border-border bg-card px-6">
          <Skeleton className="h-9 w-full max-w-xl bg-muted" />
          <div className="hidden gap-2 md:flex">
            <Skeleton className="h-9 w-32 bg-muted/80" />
            <Skeleton className="h-9 w-36 bg-muted/80" />
            <Skeleton className="h-9 w-28 bg-muted/80" />
          </div>
        </header>
        <main className="flex-1 overflow-auto p-6">
          <Skeleton className="mb-4 h-4 w-48 bg-muted/90" />
          <div className="space-y-3">
            {rows.map((_, index) => (
              <div key={index} className="flex items-center gap-4 rounded-md border border-border/80 bg-card/60 p-4">
                <Skeleton className="h-6 w-6 rounded bg-muted" />
                <Skeleton className="h-4 flex-1 bg-muted/90" />
                <Skeleton className="h-4 w-24 bg-muted/80" />
                <Skeleton className="h-4 w-20 bg-muted/80" />
                <Skeleton className="h-8 w-10 bg-muted/80" />
              </div>
            ))}
          </div>
        </main>
      </div>
    </div>
  )
}

